package cn.edu.scau.cmi.duzefeng.compositeprog.control;

import java.net.URL;
import java.util.ResourceBundle;

import cn.edu.scau.cmi.duzefeng.compositeprog.model.save.Member;
import cn.edu.scau.cmi.duzefeng.compositeprog.model.save.Organization;
import cn.edu.scau.cmi.duzefeng.compositeprog.model.save.Person;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.VBox;

public class SaveController implements Initializable {
	@FXML
	private VBox vbox;
	@FXML
	private TreeView<Member> treeView;

	@FXML
	private TextField personName;
	@FXML
	private TextField orgnName;

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		TreeItem<Member> root = new TreeItem<Member>(new Organization(""));
		treeView.setRoot(root);
	}

	@FXML
	public void addPerson(ActionEvent e){
		TreeItem<Member> treeItem = getSelectOrgnItem();
		Organization orgn = (Organization) treeItem.getValue();
		Person person = new Person(personName.getText());
		orgn.addChild(person);
		treeItem.getChildren().add(new TreeItem<Member>(person));
	}
	private TreeItem<Member> getSelectOrgnItem(){
		TreeItem<Member> treeItem = treeView.getRoot();
		if(!treeView.getSelectionModel().isEmpty()){
			if(treeView.getSelectionModel().getSelectedItem().getValue() instanceof Organization){
				treeItem = treeView.getSelectionModel().getSelectedItem();
			}
		}
		return treeItem;
	}
	@FXML
	public void addOrganization(ActionEvent e){
		TreeItem<Member> treeItem = getSelectOrgnItem();
		Organization orgn = (Organization) treeItem.getValue();
		Organization organization = new Organization(orgnName.getText());
		orgn.addChild(organization);
		treeItem.getChildren().add(new TreeItem<Member>(organization));
	}
	private TreeItem<Member> getSelectItem(){
		TreeItem<Member> treeItem = treeView.getRoot();
		if(!treeView.getSelectionModel().isEmpty()){
			treeItem = treeView.getSelectionModel().getSelectedItem();
		}
		return treeItem;
	}
	@FXML
	public void delete(ActionEvent e){
		TreeItem<Member> treeItem = getSelectItem();
		if(treeItem.getParent() != null){
			treeItem.getParent().getChildren().remove(treeItem);
			if(treeItem.getParent().getValue() instanceof Organization){
				((Organization)treeItem.getParent().getValue()).removeChild(treeItem.getValue());
			}
		}
	}

}
